﻿#define _CRT_SECURE_NO_WARNINGS 1

/*
二分查找算法
二分查找的mid本来是(left + right)/2
这里为了防止溢出就写成 left + (right - left) / 2
至于循环条件，一般是写成 left <= right
*/

//每日一题_02
//704. 二分查找
//https://leetcode.cn/problems/binary-search/description/

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left = 0;
        int right = nums.size() - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            }
            else if (nums[mid] < target) {
                left = mid + 1;
            }
            else {
                return mid;
            }
        }

        return -1;
    }
};